import React, { Fragment } from 'react';
import { connect } from 'dva';
import {
  DownloadOutlined,
  DownOutlined,
  PlusOutlined,
  UpOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import {
  Card,
  Button,
  Form,
  Table,
  Alert,
  Row,
  Col,
  Modal,
  Spin,
  Divider,
  Dropdown,
  Menu,
  Select,
  Input,
} from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';
import downloadFile from '@/utils/utils';
import { checkPermissions } from '@/utils/authority';
import Authorized from '@/utils/Authorized';
import HOCSelect from '@/components/AntDesign/Select';
import Configure from '../../components/Configure'; // 获取字典配置名称
// import Customer from '../../components/Customer'; // 获取字典客户名称
import Customer from '../../components/CustomerWithState'; // 获取字典客户名称

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

@connect(({ publicdata, serviceconfig, loading }) => ({
  dictCode: publicdata.dictCode,
  loading: loading.models.serviceconfig,
  pageData: serviceconfig.pageData,
  formFieldsValue: serviceconfig.formFieldsValue,
  valuesArr: serviceconfig.valuesArr,
  expandForm: serviceconfig.expandForm,
  respUserList: serviceconfig.respUserList,
}))

class BasicList extends React.Component {
  formRef = React.createRef()

  constructor(props) {
    super(props);
    this.state = {
      formValues: {},
      selectedRowKeys: [],
      selectedRows: [],
    };
    // 表单布局
    this.formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'serviceconfig/fetchRespUserList',
      payload: {},
    });
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
    } = this.props;
    if (location.queryParam) {
      dispatch({
        type: 'serviceconfig/updateModelData',
        payload: { formFieldsValue: location.queryParam },
      });
    }
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = async () => {
    const { valuesArr, dispatch } = this.props;
    const values = await this.formRef.current.validateFields(valuesArr);
    await dispatch({
      type: 'serviceconfig/updateModelData',
      payload: {
        formFieldsValue: values,
      },
    });
    this.searchList(this.processFormData(values));
  };

  // 查询
  searchList = (formFieldsValue, currentPage = 1, pageSize = 10, isClear = true) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }

    const { dispatch } = this.props;
    const pageArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'serviceconfig/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'serviceconfig/fetchList',
      payload: values,
    });

    this.setState({
      formValues: formFieldsValue,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'custConfNo') {
        tempFieldsValue[key] = (fieldsValue[key] && fieldsValue[key].trim()) || null;
      }
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
    });
    return formFieldsValue;
  };

  // 导出数据
  export = () => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      Modal.confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    const { formValues, selectedRowKeys } = this.state;
    const params = {
      ...formValues,
      custConfIds: selectedRowKeys,
    };
    downloadFile(params, '/csApi/custService/export', 'POST');
  };

  // 重置
  resetSearch = async () => {
    const { dispatch } = this.props;
    await dispatch({
      type: 'serviceconfig/updateModelData',
      payload: { formFieldsValue: {} },
    });
    this.formRef.current.resetFields();
    this.state.selectedRowKeys = [];
    this.state.selectedRows = [];
  };

  // 查看详情
  toDetail = (e, record) => {
    e.preventDefault();
    router.push(
      encodeURI(
        `/customservicemanage/serverconfig/detail?custConfId=${record.custConfId}&custId=${
          record.custId
        }`
      )
    );
  };

  // 删除当前rowTable数据
  delTableData = record => {
    this.setState({ selectedRowKeys: [record.custConfId] });
    const { dispatch } = this.props;
    confirm({
      icon: <QuestionCircleOutlined />,
      title: '你确定要删除此条数据吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        const values = {
          custConfId: record.custConfId,
        };
        dispatch({
          type: 'serviceconfig/delfetchList',
          payload: values,
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  handleAdd = async () => {
    const { dispatch } = this.props;
    await dispatch({
      type: 'publicdata/clearCustomerComponentData',
    });
    await dispatch({
      type: 'serviceconfig/updateModelData',
      payload: { formFieldsValue: {} },
    });
    this.formRef.current.resetFields();
    router.push('/customservicemanage/serverconfig/add');
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'serviceconfig/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  renderSimpleForm() {
    const {
      formFieldsValue,
    } = this.props;
    return (
      <Form ref={this.formRef} initialValues={formFieldsValue}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="配置编号" name="custConfNo">
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="客户名称" {...this.formItemLayout} name="custId">
              <Customer allowClear />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={this.searchBtnList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      formFieldsValue,
      respUserList,
    } = this.props;
    return (
      <Form ref={this.formRef} initialValues={formFieldsValue}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="配置编号" {...this.formItemLayout} name="custConfNo">
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="客户名称" {...this.formItemLayout} name="custId">
              <Customer allowClear />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="配置名称" {...this.formItemLayout} name="custConfId">
              <Configure allowClear />
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="所属客服" {...this.formItemLayout} name="primId">
              <HOCSelect
                placeholder="请输入关键字检索"
                style={{ width: '100%' }}
                showSearch
                optionFilterProp="children"
                allowClear
              >
                {respUserList.map(item => (
                  <Option key={item.userId} title={item.userName}>
                    {item.userName}
                  </Option>
                  ))}
              </HOCSelect>
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" style={{ marginTop: '5px' }} onClick={this.searchBtnList}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { selectedRowKeys } = this.state;
    const { pageData, loading, formFieldsValue } = this.props;
    const total = pageData && pageData.pagination.total;

    // 表格配置：行选择
    const rowSelection = {
      selectedRowKeys,
      onChange: rows => {
        this.setState({ selectedRowKeys: rows });
      },
    };

    // 表格配置：分页器
    const pagination = {
      defaultCurrent: pageData.pagination.current, // 默认当前页
      defaultPageSize: pageData.pagination.pageSize, // 默认单页条数
      current: pageData.pagination.current, // 当前页
      pageSize: pageData.pagination.pageSize, // 单页条数
      total, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onChange: (page, pageSize) => {
        this.searchList(this.processFormData(formFieldsValue), page, pageSize);
      },
      onShowSizeChange: (current, size) => {
        this.searchList(this.processFormData(formFieldsValue), current, size);
      },
      showTotal: totals => {
        const totalPage =
          totals < pagination.pageSize ? 1 : Math.ceil(totals / pagination.pageSize);
        return `共 ${total} 条记录 第 ${pagination.current} / ${totalPage}页`;
      },
    };

    // 表格字段
    const columns = [
      {
        title: '配置编号',
        dataIndex: 'custConfNo',
        width: 200,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '配置名称',
        dataIndex: 'custConfName',
        width: 200,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '客户',
        dataIndex: 'custName',
        width: 200,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <div className="editable-row-operations">{text}</div>,
      },
      {
        title: '备注',
        width: 200,
        dataIndex: 'remark',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && val) || '--',
      },
      {
        title: '所属客服',
        dataIndex: 'primName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && val) || '--',
      },
      {
        title: '操作',
        dataIndex: 'operations',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <div className="editable-row-operations">
            <a onClick={e => this.toDetail(e, record)}>查看</a>
            <Divider type="vertical" />
            <Dropdown
              overlay={
                <Menu>
                  {checkPermissions('cs:custService:update') && (
                    <Menu.Item
                      key="update"
                      onClick={() => {
                        router.push(
                          `/customservicemanage/serverconfig/update?custConfId=${record.custConfId}`
                        );
                      }}
                    >
                      修改
                    </Menu.Item>
                  )}
                  {checkPermissions('cs:custService:delete') && (
                    <Menu.Item key="delete" onClick={() => this.delTableData(record)}>
                      删除
                    </Menu.Item>
                  )}
                </Menu>
              }
            >
              <a>
                更多
                <DownOutlined />
              </a>
            </Dropdown>
          </div>
        ),
      },
    ];

    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <Card className={styles.searchCard}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
          </Card>
          <Card className={styles.tableCard}>
            <Row>
              <Authorized authority="cs:custService:insert" noMatch={null}>
                <Button type="primary" onClick={this.handleAdd} style={{ marginRight: 8 }}>
                  <PlusOutlined />
                  新增
                </Button>
              </Authorized>
              <Authorized authority="cs:custServiceConf:batchAdd" noMatch={null}>
                <Button
                  onClick={() => router.push('/customservicemanage/serverconfig/batchadd')}
                  style={{ marginRight: 8 }}
                >
                  批量新增
                </Button>
              </Authorized>
              <Authorized authority="cs:custService:queryList" noMatch={null}>
                <Button onClick={this.export}>
                  <DownloadOutlined />
                  导出
                </Button>
              </Authorized>
            </Row>
            <Alert
              style={{
                margin: '16px 0 15px 0',
              }}
              message={
                <Fragment>
                  <span style={{ fontWeight: 'bold' }}>
                    在遇到以下几种情况时需要在增员时使用服务配置：
                  </span>
                  ①一个客户下有多个单立户 ②社保五险缴费方式不同 ③社保五险缴费账户不同
                  ④大库不用默认社保组合需要指定
                </Fragment>
              }
              type="info"
              showIcon
            />
            <Table
              rowSelection={rowSelection}
              dataSource={pageData && pageData.list}
              rowKey={record => record.custConfId}
              columns={columns}
              pagination={pagination}
              bordered
            />
          </Card>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default BasicList;
